<template>
  <div class="evaluations-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-select
              v-model="unitFilter"
              placeholder="实习单位筛选"
              clearable
              @change="handleSearch"
              style="width: 200px"
            >
              <el-option
                v-for="unit in units"
                :key="unit.id"
                :label="unit.unitName"
                :value="unit.id"
              />
            </el-select>
            
            <el-select
              v-model="graduateFilter"
              placeholder="毕业生筛选"
              clearable
              @change="handleSearch"
              style="width: 200px"
            >
              <el-option
                v-for="graduate in graduates"
                :key="graduate.id"
                :label="graduate.graduateName"
                :value="graduate.id"
              />
            </el-select>
            
            <el-select
              v-model="indicatorFilter"
              placeholder="指标点筛选"
              clearable
              @change="handleSearch"
              style="width: 200px"
            >
              <el-option
                v-for="indicator in indicators"
                :key="indicator.id"
                :label="indicator.indicatorName"
                :value="indicator.id"
              />
            </el-select>
            
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </div>
          
          <el-button
            type="primary"
            :icon="Plus"
            @click="handleAdd"
            v-if="userStore.isAdmin || userStore.isInternshipUnit"
          >
            新增评价
          </el-button>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="evaluations"
        border
        style="width: 100%"
      >
        <el-table-column label="指标点" min-width="200">
          <template #default="{ row }">
            {{ getIndicatorName(row.indicatorId) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="score" label="评价分数" width="120">
          <template #default="{ row }">
            {{ row.score }}
          </template>
        </el-table-column>
        
        <el-table-column prop="description" label="评价说明" min-width="300" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="evaluation-description">{{ row.description }}</div>
          </template>
        </el-table-column>

        <el-table-column label="评价单位" min-width="120">
          <template #default="{ row }">
            {{ row.internshipUnitName }}
          </template>
        </el-table-column>
        
        <el-table-column label="被评价学生" min-width="120">
          <template #default="{ row }">
            {{ row.graduateName }}
          </template>
        </el-table-column>
        
        <el-table-column prop="evaluationTime" label="评价时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.evaluationTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              :icon="Edit"
              @click="handleEdit(row)"
              v-if="userStore.isAdmin || userStore.isInternshipUnit"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              :icon="Delete"
              @click="handleDelete(row)"
              v-if="userStore.isAdmin"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 评价表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增评价' : '编辑评价'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="实习单位" prop="internshipUnitId">
          <el-select
            v-model="form.internshipUnitId"
            placeholder="请选择实习单位"
            style="width: 100%"
            :disabled="userStore.isInternshipUnit"
          >
            <el-option
              v-for="unit in units"
              :key="unit.id"
              :label="unit.unitName"
              :value="unit.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="毕业生" prop="studentId">
          <el-select
            v-model="form.studentId"
            placeholder="请选择毕业生"
            style="width: 100%"
          >
            <el-option
              v-for="graduate in graduates"
              :key="graduate.id"
              :label="graduate.graduateName"
              :value="graduate.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="指标点" prop="indicatorId">
          <el-select
            v-model="form.indicatorId"
            placeholder="请选择指标点"
            style="width: 100%"
          >
            <el-option
              v-for="indicator in indicators"
              :key="indicator.id"
              :label="indicator.indicatorName"
              :value="indicator.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="评价分数" prop="score">
          <el-input-number
            v-model="form.score"
            :min="1"
            :max="5"
            :precision="0"
            :step="1"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="评价说明" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入评价说明"
          />
        </el-form-item>

        <el-form-item label="评价时间" prop="evaluationTime">
          <el-date-picker
            v-model="form.evaluationTime"
            type="datetime"
            placeholder="请选择评价时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '../store'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import request from '../api/request'

const userStore = useUserStore()
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const unitFilter = ref('')
const graduateFilter = ref('')
const indicatorFilter = ref('')
const evaluations = ref([])
const units = ref([])
const graduates = ref([])
const indicators = ref([])

const form = reactive({
  id: null,
  internshipUnitId: null,
  studentId: null,
  indicatorId: null,
  score: 1,
  description: '',
  evaluationTime: new Date()
})

const rules = {
  internshipUnitId: [
    { required: true, message: '请选择实习单位', trigger: 'change' }
  ],
  studentId: [
    { required: true, message: '请选择毕业生', trigger: 'change' }
  ],
  indicatorId: [
    { required: true, message: '请选择指标点', trigger: 'change' }
  ],
  score: [
    { required: true, message: '请输入评价分数', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入评价说明', trigger: 'blur' }
  ],
  evaluationTime: [
    { required: true, message: '请选择评价时间', trigger: 'change' }
  ]
}

const fetchEvaluations = async () => {
  try {
    loading.value = true
    const res = await request.get('/api/internship-unit-evaluations', {
      params: {
        internshipUnitId: unitFilter.value,
        studentId: graduateFilter.value,
        indicatorId: indicatorFilter.value
      }
    })
    evaluations.value = res.data.records
  } catch (error) {
    console.error('获取评价列表失败:', error)
  } finally {
    loading.value = false
  }
}

const fetchIndicators = async () => {
  try {
    const res = await request.get('/api/indicators')
    indicators.value = res.data
  } catch (error) {
    console.error('获取指标点列表失败:', error)
  }
}

const handleSearch = () => {
  fetchEvaluations()
}

const resetSearch = () => {
  unitFilter.value = ''
  graduateFilter.value = ''
  indicatorFilter.value = ''
  fetchEvaluations()
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    id: null,
    internshipUnitId: userStore.isInternshipUnit ? userStore.userId : null,
    studentId: null,
    indicatorId: null,
    score: 1,
    description: '',
    evaluationTime: new Date()
  })
}

const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, {
    id: row.id,
    internshipUnitId: row.internshipUnitId,
    studentId: row.studentId,
    indicatorId: row.indicatorId,
    score: row.score,
    description: row.description,
    evaluationTime: new Date(row.evaluationTime)
  })
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该评价记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await request.delete(`api/internship-unit-evaluations/${row.id}`)
    ElMessage.success('删除成功')
    fetchEvaluations()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

const handleSubmit = async () => {
  try {
    const formData = { ...form };
    
    // 确保 evaluationTime 是正确的格式
    if (formData.evaluationTime) {
      if (formData.evaluationTime instanceof Date) {
        formData.evaluationTime = formData.evaluationTime.toISOString();
      } else if (typeof formData.evaluationTime === 'string') {
        // 如果是字符串，确保它是 ISO 格式
        const date = new Date(formData.evaluationTime);
        if (!isNaN(date.getTime())) {
          formData.evaluationTime = date.toISOString();
        } else {
          ElMessage.error('评价时间格式不正确');
          return;
        }
      }
    }

    console.log('提交的数据:', formData);
    
    if (formData.id) {
      // 更新
      const response = await request.put(`/api/internship-unit-evaluations/${formData.id}`, formData);
      console.log('更新响应:', response);
      if (response.code === 200) {
        ElMessage.success('更新成功');
        dialogVisible.value = false;
        fetchEvaluations();
      } else {
        ElMessage.error(response.msg || '更新失败');
      }
    } else {
      // 创建
      const response = await request.post('/api/internship-unit-evaluations', formData);
      console.log('创建响应:', response);
      if (response.code === 200) {
        ElMessage.success('创建成功');
        dialogVisible.value = false;
        fetchEvaluations();
      } else {
        ElMessage.error(response.msg || '创建失败');
      }
    }
  } catch (error) {
    console.error('提交错误:', error);
    if (error.response) {
      console.error('错误响应:', error.response.data);
      ElMessage.error(error.response.data.message || '操作失败');
    } else {
      ElMessage.error('操作失败: ' + error.message);
    }
  }
};

const getIndicatorName = (indicatorId) => {
  const indicator = indicators.value.find(i => i.id === indicatorId)
  return indicator ? indicator.indicatorName : ''
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  try {
    const date = new Date(dateTime);
    if (isNaN(date.getTime())) return '';
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    });
  } catch (error) {
    console.error('日期格式化错误:', error);
    return '';
  }
};

onMounted(async () => {
  await Promise.all([
    fetchEvaluations(),
    fetchIndicators()
  ])
})
</script>

<style scoped>
.evaluation-description {
  white-space: pre-wrap;
  line-height: 1.5;
  color: #606266;
}

.evaluations-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  gap: 10px;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 